package com.hue.netty.day01.three;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ServerHandler extends SimpleChannelInboundHandler<String> {
    //创建channelGroup,保存所有的客户端channel(所有的socketChannel都应该在一个集合中，所以channelGroup必需是static的)
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //接收消息并并转发
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println(channelHandlerContext.channel().remoteAddress() + "发送了消息:" + s);
        //将接收到的消息发送给其他用户(channelGroup会迭代所有channel)
        channelGroup.forEach(channel -> {
            if (channel != channelHandlerContext.channel()) {
                channel.writeAndFlush(s);
            }
        });
    }

    //用户上线时触发
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        channelGroup.add(ctx.channel());
        System.out.println(ctx.channel().remoteAddress() + "上线了...");
    }

    //用户下线时触发
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "下线了...");
    }

    //发生异常时
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
